package column

import (
	"fmt"
	"game/game-db/orm/metag"
	"reflect"
	"strconv"
	"strings"
	"unsafe"
)

type BoolColumnMeta struct {
	ColumnMeta
}

func (t *BoolColumnMeta) FillValue(objField reflect.Value, fieldValue reflect.Value) {
	if objField.CanSet() {
		boolStr := fieldValue.Interface().(string)
		value, err := strconv.ParseBool(boolStr)
		if err != nil {
			fmt.Printf("字段%v在解释值%v时发生错误%v\n", t.fieldName, boolStr, err)
		} else {
			objField.SetBool(value)
		}
	} else {
		objField = reflect.NewAt(objField.Type(), unsafe.Pointer(objField.UnsafeAddr())).Elem()
		boolStr := fieldValue.Interface().(string)
		value, err := strconv.ParseBool(boolStr)
		if err != nil {
			fmt.Printf("字段%v在解释值%v时发生错误%v\n", t.fieldName, boolStr, err)
		} else {
			objField.SetBool(value)
		}
	}
}

func (t *BoolColumnMeta) TakeValue(objField reflect.Value) interface{} {
	var value interface{}
	if objField.CanInterface() {
		value = objField.Interface()
	} else {
		objField = reflect.NewAt(objField.Type(), unsafe.Pointer(objField.UnsafeAddr())).Elem()
		value = objField.Interface()
	}
	boolean := value.(bool)
	if boolean {
		return "true"
	} else {
		return "false"
	}
}

func (t *BoolColumnMeta) DbColumnType() string {
	return "char(5)"
}

func (t *BoolColumnMeta) DefaultValue() string {
	return "DEFAULT 'false'"
}

func (t *BoolColumnMeta) IsChange(dbColumnType string, dbColumnExtra string) bool {
	return !strings.HasPrefix(dbColumnType, "char(5)")
}

func NewBoolField(structField reflect.StructField, columnMetag metag.ColumnMetag) IColumnMeta {
	var meta BoolColumnMeta
	meta.fillBaseValue(structField, columnMetag)
	return &meta
}
